const glob = require('glob');
const path = require('path');
const errors = require('./errors.js');
const Connector = require('./mysql.js');
const bodyKeys = ['id','method','jsonrpc'];
const mysql = new Connector();

const lab = Object.create(null);
lab.mysql = mysql;

const isKitty = function(file) {
    const entry = glob.sync(path.join(__dirname,'..','..','..','**/conf/hako.json'));
    const { kitties } = require(entry[0]);
    let arr = Object.keys(kitties);
    for(let item of arr) {
        if(file.indexOf(item) >= 0) {
            return true;
        }
    }
    return false
}

void function() {
    const entries = glob.sync(path.join(__dirname,'..','..','**/service/**/*.js'));
    entries.forEach(entry=> {
        let arr = entry.split('/');
        let index = arr.findIndex(item=> {
            if(item == 'service') {
                return item
            }
        })
        lab[arr[index-1]] ? '' : lab[arr[index-1]] = {};
        let funtors = require(entry)(lab);
        if(!arr[index+1].endsWith('.js')) {
            lab[arr[index-1]][arr[index+1]] ? '' : lab[arr[index-1]][arr[index+1]] = {}
            lab[arr[index-1]][arr[index+1]] = Object.assign({},lab[arr[index-1]][arr[index+1]],funtors)
        } else {
            let key = arr[index+1].split('.js')[0];
            lab[arr[index-1]][key] ? '' : lab[arr[index-1]][key] = {};
            lab[arr[index-1]][key] = funtors
        }
    })
}();

const getfunctor = function(method,object) {
    let path = method.split('.');
    let index = 0
    const length = path.length

    while (object != null && index < length) {
        object = object[path[index++]]
    }
    return (index && index == length) ? object : undefined
}

module.exports = function(req,res,next) {
    let start_time = Date.now();
    if(req.method != 'POST') {
        next()
    } else {
        const body = Object.create(null);
        for (let key of bodyKeys) {
            if(!req.body[key]) {
                res.send(errors.no_permission)
                return;
            }
            body[key] = req.body[key];
        }
        let functor = getfunctor(body.method, lab);
        if(!functor) {
            res.send(errors.method_not_found)
            return;
        } else {
            return functor(req.session,body.params).then(result=> {
                res.send({
                    id: body.id,
                    result
                })
                let time_used = Date.now() - start_time;
                $info(`RPC server request: ${body.method}, takes : ${time_used} ms`)
            })
        }
    }
}